/*
 * @Author: Zhang Wei
 * @Date: 2022-08-09 09:23:03
 * @LastEditors: Zhang Wei
 * @LastEditTime: 2022-12-14 20:15:28
 * @FilePath: /hj-uni-common/src/H5Common/wechart/index.js
 * @Word: There is nothing either good or bad, but thinking makes it so.
 * @Description:
 */
// 拆分代码
import { pay } from './pay.js';
import { scanCode } from './scanCode.js';
import { openLocation } from './openLocation.js';

export const WxObj = {
  // 系统appid
  sysAppid: null,

  // 获取微信授权的接口
  jsApi: null,

  // 微信对象
  wx: null,

  // 构造器
  init(sysAppid, jsApi, wx) {
    this.sysAppid = sysAppid;
    this.jsApi = jsApi;
    this.wx = wx;

    return this;
  },

  // 登录
  // login() {}

  // 支付
  pay(data) {
    return pay(data, this.wx);
  },

  // 扫码
  async scanCode(options) {
    let data = await this.jsCheck();
    scanCode(options, data, this.wx);
  },

  // 位置信息
  async openLocation(options) {
    let data = await this.jsCheck();
    openLocation(options, data, this.wx);
  },

  // api接口
  async jsCheck() {
    let { sysAppid, jsApi } = this;
    let url = window.location.href.split('#')[0];

    let query = {
      url,
      sysAppid,
    };

    let res = await jsApi(query);
    if (res && (!res.success || !res.data)) {
      if (!res.message) res.message = '接口请求出错';
      return Promise.reject(res);
    }

    return Promise.resolve(res.data || {});
  },
};
